package com.chookss.home.audit.clockIn;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.MyAuditRecordActivity;
import com.chookss.home.audit.service.UploadHolidayService;
import com.chookss.home.audit.AuditActivity;
import com.chookss.home.audit.adapter.FilesHolidyAdapter;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.ClockInGroupEntity;
import com.chookss.home.entity.HolidayDetailEntity;
import com.chookss.home.entity.ReimbursementTypeEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.filePicker.FilePicker;
import com.chookss.tools.filePicker.model.EssFile;
import com.chookss.tools.filePicker.util.Const;
import com.chookss.tools.filePicker.util.FileSizeUtil;
import com.chookss.tools.filePicker.util.FileUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BasisTimesUtils;
import com.chookss.view.DrawableTextView;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.LogBottomDialog;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.chookss.view.listener.ShareChoiceDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClockInAskHolidayActivity extends BaseAct {
//请假首页

    @BindView(R.id.tvType)
    DrawableTextView tvType;
    @BindView(R.id.tvGroup)
    DrawableTextView tvGroup;
    @BindView(R.id.tvStartTime)
    DrawableTextView tvStartTime;
    @BindView(R.id.tvEndTime)
    DrawableTextView tvEndTime;
    @BindView(R.id.tvTimeLength)
    TextView tvTimeLength;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.llGroup)
    LinearLayout llGroup;
    @BindView(R.id.groupEmpty)
    View groupEmpty;
    @BindView(R.id.ivAudit)
    ImageView ivAudit;
    @BindView(R.id.fileRcv)
    RecyclerView fileRcv;
    private static final int REQUEST_CODE_CHOOSE = 23;
    private List<HolidayDetailEntity.AnnexsBean> filesList = new ArrayList<>();
    private FilesHolidyAdapter adapter;
    private HolidayDetailEntity holidayDetailEntity = null;
    private int currentStart = 0, currentEnd = 0;//0上午1下午
    private List<ReimbursementTypeEntity> holidayTypeEntities = new ArrayList<>();
    private List<ClockInGroupEntity> groupEntities = new ArrayList<>();
    private String[] groupArray = null;
    private String[] holidayArray = null;
    private String qingjiaWorkflowCode = "", workflowId = "";//不为空说明是修改进来的
    private String groupCode = "", groupName = "", holidyCode = "";
    private String holidyName = "";//还款类型名称
    private float timeLimit = 15;//请假类型最多多少天
    private boolean errorStatus = false;//true 说明是上传失败进来
    private String tag = "ClockInAskHolidayActivity_DownloadFile";//下载文件打的标签
    private LogBottomDialog bottomDialog = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_in_ask_holiday);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this, "1", "28");
        qingjiaWorkflowCode = getIntent().getStringExtra("qingjiaWorkflowCode");
        workflowId = getIntent().getStringExtra("workflowId");
        errorStatus = getIntent().getBooleanExtra("errorStatus", false);
        fileRcv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new FilesHolidyAdapter(R.layout.item_files_list, this, filesList, 0, tag);
        fileRcv.setAdapter(adapter);
        if (errorStatus) {
            //上传失败进来的
            holidayDetailEntity = (HolidayDetailEntity) getIntent().getSerializableExtra("data");
            tvSure.setText("重新提交");
            setErrorData();
        } else {
            holidayDetailEntity = new HolidayDetailEntity();
            List<HolidayDetailEntity.AnnexsBean> annexsBeanList = new ArrayList<>();
            holidayDetailEntity.setAnnexs(annexsBeanList);
        }
        getGroupList();
        getHolidayList();
        getworkList();
        if (!Utils.isNull(qingjiaWorkflowCode)) {
            selectKaoqinDeail();
            tvSure.setText("重新提交");
            registerBoradcastReceiver();
        }
    }

    private void setErrorData() {
        //上传失败后数据的初始化
        if (holidayDetailEntity != null) {
            groupCode = holidayDetailEntity.getGroupCode();
            groupName = holidayDetailEntity.getItemGroupName();
            holidyCode = holidayDetailEntity.getBaoixaoTypeCode();
            holidyName = holidayDetailEntity.getBaoixaoTypeName();
            if (!Utils.isNull(holidayDetailEntity.getGroupCode())) {
                tvGroup.setText(holidayDetailEntity.getItemGroupName() + "(" + ClockInUtils.getGroupEnd(holidayDetailEntity.getGroupCode()) + ")");
                groupEmpty.setVisibility(View.VISIBLE);
                llGroup.setVisibility(View.VISIBLE);
            }
            tvTimeLength.setText(holidayDetailEntity.getQingjiaLength());
            if (!Utils.isNull(holidayDetailEntity.getStartTime())) {
                if (holidayDetailEntity.getStartTime().length() >= 10) {
                    tvStartTime.setText(holidayDetailEntity.getStartTime());
                    if (holidayDetailEntity.getStartTime().endsWith("下午")) {
                        currentStart = 1;
                    } else {
                        currentStart = 0;
                    }
                    mYear = Utils.changeNumber(holidayDetailEntity.getStartTime().substring(0, 4));
                    monthS = holidayDetailEntity.getStartTime().substring(5, 7);
                    dayS = holidayDetailEntity.getStartTime().substring(8, 10);
                }
            }
            if (!Utils.isNull(holidayDetailEntity.getEndTime())) {
                if (holidayDetailEntity.getEndTime().length() >= 10) {
                    tvEndTime.setText(holidayDetailEntity.getEndTime());
                    if (holidayDetailEntity.getEndTime().endsWith("下午")) {
                        currentEnd = 1;
                    } else {
                        currentEnd = 0;
                    }
                    mYear2 = Utils.changeNumber(holidayDetailEntity.getEndTime().substring(0, 4));
                    monthS2 = holidayDetailEntity.getEndTime().substring(5, 7);
                    dayS2 = holidayDetailEntity.getEndTime().substring(8, 10);
                }

            }
            tvType.setText(holidayDetailEntity.getBaoixaoTypeName());
            if (Utils.isNull(holidayDetailEntity.getRemark())) {
                edContent.setText("无");
            } else {
                edContent.setText(holidayDetailEntity.getRemark());
            }
            filesList.clear();
            filesList.addAll(holidayDetailEntity.getAnnexs());
            adapter.notifyDataSetChanged();
            getHolidayNameList(true);
        }
    }

    private void getGroupList() {
        //项目组基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInGroupEntity>>>() {
        }.getType(), null, Urls.selectMyItemGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<ClockInGroupEntity>>() {
            @Override
            public void onSuccess(List<ClockInGroupEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvTimeLength == null) {
                        return;
                    }
                    groupEntities.addAll(data);
                    groupArray = new String[groupEntities.size()];
                    for (int i = 0; i < groupEntities.size(); i++) {
                        if ("1".equals(groupEntities.get(i).getMainCd())) {
                            groupArray[i] = groupEntities.get(i).getGroupName() + "[常驻]";
                        } else {
                            groupArray[i] = groupEntities.get(i).getGroupName();
                        }

                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getHolidayList() {
        //获取请假类型列表
        Map<String, String> map = new HashMap<>();
        map.put("type", "4");//(1-报销 2-借款 3物品4请假
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<ReimbursementTypeEntity>>>() {
        }.getType(), null, Urls.selectBaoxiaoTypeList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ReimbursementTypeEntity>>() {
            @Override
            public void onSuccess(List<ReimbursementTypeEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvTimeLength == null) {
                        return;
                    }
                    holidayTypeEntities.clear();
                    holidayTypeEntities.addAll(data);
                    holidayArray = new String[holidayTypeEntities.size()];
                    for (int i = 0; i < holidayTypeEntities.size(); i++) {
                        holidayArray[i] = holidayTypeEntities.get(i).getBaoixaoTypeName();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void getHolidayNameList(boolean isEdit) {
        //获取报销名称列表
        Map<String, String> map = new HashMap<>();
        map.put("baoixaoTypeCode", holidyCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<ReimbursementTypeEntity>>() {
        }.getType(), null, Urls.selectBaoxiaoInfDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementTypeEntity>() {
            @Override
            public void onSuccess(ReimbursementTypeEntity data) {
                if (tvType == null) {
                    return;
                }
                if(isEdit){
                    //修改或者本地缓存数据 需要设置一下是否需要附件
                    for (int i = 0; i < data.getAnnexs().size(); i++) {
                        filesList.get(i).setNeedCd(data.getAnnexs().get(i).getNeedCd());
                    }
                }else {
                    holidayDetailEntity.getAnnexs().clear();
                    filesList.clear();
                    for (int i = 0; i < data.getAnnexs().size(); i++) {
                        HolidayDetailEntity.AnnexsBean annexsBean = new HolidayDetailEntity.AnnexsBean();
                        annexsBean.setAnnexName(data.getAnnexs().get(i).getAnnexName());
                        annexsBean.setBaoixaoTypeCode(holidyCode);
                        annexsBean.setNeedCd(data.getAnnexs().get(i).getNeedCd());
                        List<HolidayDetailEntity.AnnexsBean.PictureInfoListBean> list = new ArrayList<>();
                        annexsBean.setPictureInfoList(list);
                        List<HolidayDetailEntity.AnnexsBean.DatabaseBean> list2 = new ArrayList<>();
                        annexsBean.setDatabase(list2);
                        holidayDetailEntity.getAnnexs().add(annexsBean);
                    }
                    filesList.addAll(holidayDetailEntity.getAnnexs());
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void selectKaoqinDeail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", qingjiaWorkflowCode);
        map.put("type", "4");//3补卡 4请假
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<HolidayDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<HolidayDetailEntity>() {
            @Override
            public void onSuccess(HolidayDetailEntity data) {
                if (data != null) {
                    if (tvTimeLength == null) {
                        return;
                    }
                    groupCode = data.getGroupCode();
                    groupName = data.getItemGroupName();
                    holidyCode = data.getBaoixaoTypeCode();
                    holidyName=data.getBaoixaoTypeName();
                    if (!Utils.isNull(data.getGroupCode())) {
                        tvGroup.setText(data.getItemGroupName() + "(" + ClockInUtils.getGroupEnd(data.getGroupCode()) + ")");
                        groupEmpty.setVisibility(View.VISIBLE);
                        llGroup.setVisibility(View.VISIBLE);
                    }
                    tvTimeLength.setText(data.getQingjiaLength() + "天");
                    if (!Utils.isNull(data.getStartTime())) {
                        if (data.getStartTime().length() >= 10) {
                            tvStartTime.setText(data.getStartTime());
                            if (data.getStartTime().endsWith("下午")) {
                                currentStart = 1;
                            } else {
                                currentStart = 0;
                            }
                            mYear = Utils.changeNumber(data.getStartTime().substring(0, 4));
                            monthS = data.getStartTime().substring(5, 7);
                            dayS = data.getStartTime().substring(8, 10);
                        }
                    }
                    if (!Utils.isNull(data.getEndTime())) {
                        if (data.getEndTime().length() >= 10) {
                            tvEndTime.setText(data.getEndTime());
                            if (data.getEndTime().endsWith("下午")) {
                                currentEnd = 1;
                            } else {
                                currentEnd = 0;
                            }
                            mYear2 = Utils.changeNumber(data.getEndTime().substring(0, 4));
                            monthS2 = data.getEndTime().substring(5, 7);
                            dayS2 = data.getEndTime().substring(8, 10);
                        }

                    }
                    tvType.setText(holidyName);
                    if (Utils.isNull(data.getRemark())) {
                        edContent.setText("无");
                    } else {
                        edContent.setText(data.getRemark());
                    }
                    filesList.clear();
                    filesList.addAll(data.getAnnexs());
                    adapter.notifyDataSetChanged();
                    getHolidayNameList(true);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getworkList();
        if (bottomDialog != null) {
            bottomDialog.dismiss();
        }
    }

    private void getworkList() {
        Map<String, String> map = new HashMap<>();
        //待审核 传0 已审核不传
        map.put("auditStatus", "0");
        map.put("pageNum", "1");
        map.put("pageSize", "1");
        // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文
        map.put("type", "4");

        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<WorkNewEntity>>>() {
        }.getType(), null, Urls.selectKqMyWorkList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<WorkNewEntity>>() {
            @Override
            public void onSuccess(List<WorkNewEntity> data) {
                if (ivAudit == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    ivAudit.setVisibility(View.VISIBLE);
                } else {
                    ivAudit.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                if (ivAudit != null) {
                    ivAudit.setVisibility(View.GONE);
                }
            }
        });
    }
    private void requestCamera(int type, int fileNum) {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            if (type == 0) {
                                //选图片
                                PictureSelector.create(ClockInAskHolidayActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxSelectNum(9 - fileNum)
                                        .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                        .isPreviewImage(true)//是否支持预览图片
                                        .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            } else {
                                //选文档
                                FilePicker
                                        .from(ClockInAskHolidayActivity.this)
                                        .chooseForMimeType()
                                        .setMaxCount(9 - fileNum)
                                        .setFileTypes("pdf", "doc", "ppt", "xls")
                                        .requestCode(REQUEST_CODE_CHOOSE)
                                        .start();
                            }

                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(ClockInAskHolidayActivity.this, denied, quick);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                if (tvType == null) {
                    return;
                }
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    if (parentNum >= 0) {
                        HolidayDetailEntity.AnnexsBean.PictureInfoListBean pictureInfoListBean = new HolidayDetailEntity.AnnexsBean.PictureInfoListBean();
                        pictureInfoListBean.setPictureUrl(url);
                        pictureInfoListBean.setLocPictureUrl(url);
                        pictureInfoListBean.setAnnexName(filesList.get(parentNum).getAnnexName());
                        pictureInfoListBean.setBaoixaoTypeCode(holidyCode);
                        filesList.get(parentNum).getPictureInfoList().add(pictureInfoListBean);
                    }
                }
                if (filesList.get(parentNum).getPictureInfoList().size() > 0) {
                    adapter.notifyItemChanged(parentNum);
                }

            }
            if (requestCode == REQUEST_CODE_CHOOSE) {
                //文档选择
                ArrayList<EssFile> essFileList = data.getParcelableArrayListExtra(Const.EXTRA_RESULT_SELECTION);
                if (essFileList.size() != 0) {
                    for (int i = 0; i < essFileList.size(); i++) {
                        HolidayDetailEntity.AnnexsBean.DatabaseBean docunmentEntity = new HolidayDetailEntity.AnnexsBean.DatabaseBean();
                        docunmentEntity.setDataTitle(essFileList.get(i).getName());
                        docunmentEntity.setDataCode("");
                        docunmentEntity.setDataPath(essFileList.get(i).getAbsolutePath());
                        docunmentEntity.setUploadTime(FileUtils.getDateTime(essFileList.get(i).getAbsolutePath()));
                        docunmentEntity.setDataSize(FileSizeUtil.getAutoFileOrFilesSize((essFileList.get(i).getFile())));
                        docunmentEntity.setAnnexName(filesList.get(parentNum).getAnnexName());
                        docunmentEntity.setBaoixaoTypeCode(holidyCode);
                        KLog.i(essFileList.get(i).getAbsolutePath());
                        filesList.get(parentNum).getDatabase().add(docunmentEntity);
                    }

                } else {
                    KLog.i("essFileList.size() == 0");
                }
                if (filesList.get(parentNum).getDatabase().size() > 0) {
                    adapter.notifyItemChanged(parentNum);
                }
            }
        }

    }


    private void uploadData() {
        Intent intent = new Intent(this, UploadHolidayService.class);
        holidayDetailEntity.setProjectName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "") + "的" + tvType.getText().toString() + "申请");
        holidayDetailEntity.setStartTime(tvStartTime.getText().toString());
        holidayDetailEntity.setEndTime(tvEndTime.getText().toString());
        holidayDetailEntity.setGroupCode(groupCode);
        holidayDetailEntity.setQingjiaCode(holidyCode);
        holidayDetailEntity.setBaoixaoTypeCode(holidyCode);
        holidayDetailEntity.setBaoixaoTypeName(holidyName);
        holidayDetailEntity.setItemGroupName(groupName);
        holidayDetailEntity.setQingjiaName(tvType.getText().toString());
        holidayDetailEntity.setQingjiaLength(tvTimeLength.getText().toString());
        holidayDetailEntity.setRemark(edContent.getText().toString());
        holidayDetailEntity.setQingjiaWorkflowCode(qingjiaWorkflowCode);
        holidayDetailEntity.setWorkflowId(workflowId);
        holidayDetailEntity.setCreateTime(Utils.getCurrentTime2());
        holidayDetailEntity.setEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        holidayDetailEntity.setEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        holidayDetailEntity.setCache(System.currentTimeMillis() + "");
        holidayDetailEntity.setCacheStatus(0);
        holidayDetailEntity.getAnnexs().clear();
        holidayDetailEntity.getAnnexs().addAll(filesList);
        intent.putExtra("holidayDetailEntity", holidayDetailEntity);
        intent.putExtra("cacheStatus", 0);
        startService(intent);
        finish();
    }

    private void uploadNoFile() {
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", tvStartTime.getText().toString());
        map.put("endTime", tvEndTime.getText().toString());
        if (!Utils.isNull(groupCode)) {
            map.put("groupCode", groupCode);
        }
        map.put("remark", edContent.getText().toString());
//        map.put("qingjiaCode", holidyCode);
        map.put("baoixaoTypeCode",holidyCode);
        map.put("baoxiaoTypeName", holidyName);
        map.put("baoixaoTypeName", holidyName);
        String url = "";
        if (Utils.isNull(qingjiaWorkflowCode)) {
            url = Urls.addQingjiaInfo;
        } else {
            url = Urls.updateQingjiaInfo;
            map.put("qingjiaWorkflowCode", qingjiaWorkflowCode);
            map.put("workflowId", workflowId);
        }
        showLoading();
        MyHttpRequest.postRequestJson(url, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        MyToast.show(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }

            }
        });
    }
    int fileNum = 0;
    int parentNum = -1;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("Files_choice_parent_num")) {
                parentNum = Utils.changeNumber(map.get("Files_choice_parent_num"));
                try {
                    fileNum = filesList.get(parentNum).getPictureInfoList().size() + filesList.get(parentNum).getDatabase().size();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (fileNum >= 9) {
                    MyToast.show("附件最多上传9个");
                    return;
                }
                if (filesList.size() > parentNum) {
                    if (bottomDialog != null) {
                        bottomDialog.dismiss();
                    }
                    bottomDialog = new LogBottomDialog(this, false, new HomeBottomDialogListener() {
                        @Override
                        public void onListItemClick(int position) {
                            if (position == 0) {
                                requestCamera(0, fileNum);
                            } else if (position == 2) {
                                requestCamera(2, fileNum);
                            }
                        }
                    });
                    bottomDialog.show();
                }
            } else if (map.containsKey("deleteHolidayPic")) {
                int position = Utils.changeNumber(map.get("position"));
                int parent_position = Utils.changeNumber(map.get("parent_position"));
                if (parent_position >= 0 && position >= 0) {
                    FileUtilss.delFile(filesList.get(parent_position).getPictureInfoList().get(position).getLocPictureUrl());
                    filesList.get(parent_position).getPictureInfoList().remove(position);
                    adapter.notifyItemChanged(parent_position);
                }
            }
            if (map.containsKey("deleteHolidayDocunment")) {
                int position = Utils.changeNumber(map.get("position"));
                int parent_position = Utils.changeNumber(map.get("parent_position"));
                if (parent_position >= 0 && position >= 0) {
                    filesList.get(parent_position).getDatabase().remove(position);
                    adapter.notifyItemChanged(parent_position);
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.ll_record, R.id.ll_audit, R.id.tvType, R.id.tvGroup, R.id.tvStartTime, R.id.tvEndTime, R.id.tvSure})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.ll_record:
                intent = new Intent(this, MyAuditRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_audit:
                //审核
                intent = new Intent(this, AuditActivity.class);
                intent.putExtra("type", 4);
                startActivity(intent);
                break;
            case R.id.tvType:
                if (holidayArray == null||holidayTypeEntities.size() == 0) {
                    MyToast.show("请假类型为空，请联系管理员配置");
                    return;
                }
                new XPopup.Builder(ClockInAskHolidayActivity.this)
                        .maxWidth(Utils.dip2px(ClockInAskHolidayActivity.this, 260))
                        .maxHeight(Utils.dip2px(ClockInAskHolidayActivity.this, 300))
                        .asCenterList("请选择请假类型", holidayArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        if (!Utils.isNull(holidayTypeEntities.get(position).getTimeLimit())) {
                                            timeLimit = Float.parseFloat(holidayTypeEntities.get(position).getTimeLimit());
                                        }
                                        holidyCode = holidayTypeEntities.get(position).getBaoixaoTypeCode();
                                        holidyName = holidayTypeEntities.get(position).getBaoixaoTypeName();
                                        tvType.setText(text);
                                        getHolidayNameList(false);
                                        if ("1".equals(holidayTypeEntities.get(position).getNeedGroupCd())) {
                                            groupCode = "";
                                            groupName = "";
                                            tvGroup.setText("");
                                            groupEmpty.setVisibility(View.VISIBLE);
                                            llGroup.setVisibility(View.VISIBLE);
                                        } else {
                                            groupCode = "";
                                            groupName = "";
                                            groupEmpty.setVisibility(View.GONE);
                                            llGroup.setVisibility(View.GONE);
                                        }
                                    }
                                })
                        .show();
                break;
            case R.id.tvGroup:
                if (groupArray == null) {
                    return;
                }
                new XPopup.Builder(ClockInAskHolidayActivity.this)
                        .maxWidth(Utils.dip2px(ClockInAskHolidayActivity.this, 260))
                        .maxHeight(Utils.dip2px(ClockInAskHolidayActivity.this, 300))
                        .asCenterList("请选择项目组", groupArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        groupCode = groupEntities.get(position).getGroupCode();
                                        groupName = groupEntities.get(position).getGroupName();
                                        tvGroup.setText(text.replace("[常驻]", "") + "(" + ClockInUtils.getGroupEnd(groupEntities.get(position).getGroupCode()) + ")");
                                    }
                                })
                        .show();
                break;
            case R.id.tvStartTime:
                showDatePickStartDialog();
                break;
            case R.id.tvEndTime:
                showDatePickEndDialog();
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (Utils.isNull(tvType.getText().toString())) {
                    MyToast.show("请选择请假类型");
                    return;
                }
                if (llGroup.getVisibility() == View.VISIBLE) {
                    if (Utils.isNull(tvGroup.getText().toString())) {
                        MyToast.show("请选择项目组");
                        return;
                    }
                }
                if (Utils.isNull(tvStartTime.getText().toString())) {
                    MyToast.show("请选择开始时间");
                    return;
                }
                if (Utils.isNull(tvEndTime.getText().toString())) {
                    MyToast.show("请选择结束时间");
                    return;
                }
                if (Utils.isNull(edContent.getText().toString())) {
                    MyToast.show("请输入请假事由");
                    return;
                }
                if (Float.parseFloat((tvTimeLength.getText().toString().split("天")[0])) > timeLimit) {
                    MyToast.show(tvType.getText().toString() + "最多" + ClearMoreZeroUtil.subZeroAndDot(timeLimit + "") + "天");
                    return;
                }
                int allSize=0;
                for (int i = 0; i < filesList.size(); i++) {
                    int fileSize = filesList.get(i).getDatabase().size() + filesList.get(i).getPictureInfoList().size();
                    allSize =allSize+fileSize;
                    if(filesList.get(i).getNeedCd().equals("1")){
                        //1必传
                        if(fileSize==0){
                            MyToast.show("请选择"+filesList.get(i).getAnnexName()+"必须的附件");
                            return;
                        }
                    }
                }
                if (allSize == 0) {
                    uploadNoFile();
                } else {
                    uploadData();
                }
                break;
        }
    }

    int mYear = 0, mMonth = 0, mDay = 0;
    String dayS = "", monthS = "";

    private void showDatePickStartDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mDay == 0) {
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择日期", mYear, mMonth, mDay,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear = year;
                        mMonth = month - 1;
                        mDay = dayOfMonth;
                        if (dayOfMonth > 9) {
                            dayS = dayOfMonth + "";
                        } else {
                            dayS = "0" + dayOfMonth;
                        }
                        if (month > 9) {
                            monthS = month + "";
                        } else {
                            monthS = "0" + month;
                        }
                        tvStartTime.setText(mYear + "-" + monthS + "-" + dayS);
                        new DateChoiceDialog(ClockInAskHolidayActivity.this, new ShareChoiceDialogListener() {
                            @Override
                            public void onClick(int position) {
                                currentStart = position;
                                if (position == 0) {
                                    tvStartTime.setText(mYear + "-" + monthS + "-" + dayS + " 上午");
                                } else {
                                    tvStartTime.setText(mYear + "-" + monthS + "-" + dayS + " 下午");
                                }
                                if (!Utils.isNull(tvEndTime.getText().toString())) {
                                    if (Utils.getTimeCompareSize(mYear + "-" + monthS + "-" + dayS,
                                            mYear2 + "-" + monthS2 + "-" + dayS2) == 1) {
                                        MyToast.show("开始时间不得晚于结束时间");
                                        tvStartTime.setText("");
                                    } else if (Utils.getTimeCompareSize(mYear + "-" + monthS + "-" + dayS,
                                            mYear2 + "-" + monthS2 + "-" + dayS2) == 2) {
                                        //日期一样，但是结束时间不能比开始时间还早
                                        if (currentEnd < currentStart) {
                                            MyToast.show("开始时间不得晚于结束时间");
                                            tvStartTime.setText("");
                                        } else {
                                            tvTimeLength.setText(ClockInUtils.calculateDay(mYear + "-" + monthS + "-" + dayS,
                                                    mYear2 + "-" + monthS2 + "-" + dayS2, currentStart, currentEnd) + "天");
                                        }
                                    } else {
                                        tvTimeLength.setText(ClockInUtils.calculateDay(mYear + "-" + monthS + "-" + dayS,
                                                mYear2 + "-" + monthS2 + "-" + dayS2, currentStart, currentEnd) + "天");
                                    }
                                }
                            }
                        }).show();
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDay(0);
    }

    int mYear2 = 0, mMonth2 = 0, mDay2 = 0;
    String dayS2 = "", monthS2 = "";

    private void showDatePickEndDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mDay2 == 0) {
            mYear2 = calendar.get(Calendar.YEAR);
            mMonth2 = calendar.get(Calendar.MONTH);
            mDay2 = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择日期", mYear2, mMonth2, mDay2,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear2 = year;
                        mMonth2 = month - 1;
                        mDay2 = dayOfMonth;
                        if (dayOfMonth > 9) {
                            dayS2 = dayOfMonth + "";
                        } else {
                            dayS2 = "0" + dayOfMonth;
                        }
                        if (month > 9) {
                            monthS2 = month + "";
                        } else {
                            monthS2 = "0" + month;
                        }
                        tvEndTime.setText(mYear2 + "-" + monthS2 + "-" + dayS2);
                        new DateChoiceDialog(ClockInAskHolidayActivity.this, new ShareChoiceDialogListener() {
                            @Override
                            public void onClick(int position) {
                                currentEnd = position;
                                if (position == 0) {
                                    tvEndTime.setText(mYear2 + "-" + monthS2 + "-" + dayS2 + " 上午");
                                } else {
                                    tvEndTime.setText(mYear2 + "-" + monthS2 + "-" + dayS2 + " 下午");
                                }
                                if (!Utils.isNull(tvStartTime.getText().toString())) {
                                    if (Utils.getTimeCompareSize(mYear + "-" + monthS + "-" + dayS,
                                            mYear2 + "-" + monthS2 + "-" + dayS2) == 1) {
                                        MyToast.show("结束时间不能早于开始时间");
                                        tvEndTime.setText("");
                                    } else if (Utils.getTimeCompareSize(mYear + "-" + monthS + "-" + dayS,
                                            mYear2 + "-" + monthS2 + "-" + dayS2) == 2) {
                                        //日期一样，但是结束时间不能比开始时间还早
                                        if (currentEnd < currentStart) {
                                            MyToast.show("结束时间不能早于开始时间");
                                            tvEndTime.setText("");
                                        } else {
                                            tvTimeLength.setText(ClockInUtils.calculateDay(mYear + "-" + monthS + "-" + dayS,
                                                    mYear2 + "-" + monthS2 + "-" + dayS2, currentStart, currentEnd) + "天");
                                        }
                                    } else {
                                        tvTimeLength.setText(ClockInUtils.calculateDay(mYear + "-" + monthS + "-" + dayS,
                                                mYear2 + "-" + monthS2 + "-" + dayS2, currentStart, currentEnd) + "天");
                                    }
                                }
                            }
                        }).show();
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDay(0);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                if (encryptStatus) {
                    for (int i = 0; i < filesList.size(); i++) {
                        for (int j = 0; j < filesList.get(i).getDatabase().size(); j++) {
                            if (filesList.get(i).getDatabase().get(j).getDataCode().equals(recevierDataCode)) {
                                if (!filesList.get(i).getDatabase().get(j).isOpen()) {
                                    if (encryptStatus) {
                                        filesList.get(i).getDatabase().get(j).setOpen(true);
                                    }
                                    dealData(0, 0, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                                }

                            }
                        }
                    }
                } else {
                    int parent = 0;
                    int child = 0;
                    String datas = position + "";
                    if (datas.length() > 1) {
                        parent = Utils.changeNumber(datas.substring(0, 1));
                        child = Utils.changeNumber(datas.substring(1, 2));
                    }
                    for (int i = 0; i < filesList.get(parent).getDatabase().size(); i++) {
                        if (filesList.get(parent).getDatabase().get(i).getDataCode().equals(recevierDataCode)) {
                            if (!filesList.get(parent).getDatabase().get(i).isOpen()) {
                                if (encryptStatus) {
                                    filesList.get(parent).getDatabase().get(i).setOpen(true);
                                }
                                dealData(parent, child, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                            }

                        }
                    }
                }

            }
        }

    };

    /**
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int parent, int child, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        } else {
            if (percent > 0 && percent < 100) {
                if (adapter != null) {
                    filesList.get(parent).getDatabase().get(child).setProgress(percent);
                    adapter.setRefresh(child);
                }
            } else if (percent == 100) {
                if (adapter != null) {
                    filesList.get(parent).getDatabase().get(child).setProgress(100);
                    adapter.setRefresh(child);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(ClockInAskHolidayActivity.this, fileUrl, fileName, recevierDataCode, tag);
                        }
                    }.start();
                }


            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(tag);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bottomDialog != null) {
            bottomDialog.dismiss();
        }
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (edContent != null) {
            Utils.hideInputKeyboard(this, edContent);
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }
}
